<template>
  <div>
    <template v-if="poster">
      <div class="flex-col">
        <div class="flex">
          <div
            class="poster_wrap flex flex-a-c mr-10 overflow-hidden"
            @dragover.prevent
            @drop="drop"
            v-for="(item, index) in poster"
            :key="index"
          >
            <a-image width="187.5" height="333.5" :src="item" show-loader :preview="false" alt="活动图片" fit="cover">
            </a-image>
            <div
              class="m-absolute r-6 t-6 w-20 h-20 flex-center cursor-pointer"
              style="background: rgba(0, 0, 0, 0.5)"
              @click="deletePoster(index)"
            >
              <icon-delete class="text-size-14 textfff" />
            </div>
            <img
              :style="{
                top: picT + 'px',
                left: picL + 'px',
                objectFit: 'cover',
                width: (picW || 200 / 4) + 'px',
                height: (picW || 200 / 4) + 'px'
              }"
              class="qr_wrap"
              src="@/assets/images/app_down_code.png"
              alt="二维码"
            />
          </div>
          <a-upload
            :file-list="fileList"
            :show-file-list="false"
            :action="uploadImage()"
            :headers="{ Authorization: token }"
            :multiple="false"
            name="file"
            :on-before-upload="
              () => {
                return (loading = true)
              }
            "
            @success="handleUploadSuccess"
            @error="handleUploadError"
          >
            <template #upload-button>
              <a-button type="primary" size="small" :loading="loading">
                <template #icon>
                  <icon-to-top />
                </template>
                <span>上传</span>
              </a-button>
            </template>
          </a-upload>
        </div>
        <div class="round-10 bg64f0f6fd box-border p-m mt-10" v-if="poster.length > 0">
          <div class="font-bold mb-6">海报二维码样式</div>
          <a-space :heading="6">
            <a-button type="primary" size="mini" @click="centerPoster">
              <template #icon>
                <icon-align-center />
              </template>
              <span>水平居中</span>
            </a-button>
            <a-button type="primary" status="warning" size="mini" v-if="showReset" @click="emit('resetPoster')">
              <template #icon>
                <icon-sync />
              </template>
              <span>重置</span>
            </a-button>
          </a-space>
          <div class="flex flex-a-c mt-m">
            <label class="nowrap text666 w-26n text-align-left">宽/高度：</label>
            <a-input-number
              class="flex-1"
              :model-value="width"
              placeholder="请输入"
              :min="0"
              :max="750"
              @change="inputChangeWidth"
            />
          </div>
          <!-- <div class="flex flex-a-c mt-m">
            <label class="nowrap text666 w-26n text-align-left">高度：</label>
            <a-input-number
              class="flex-1"
              :model-value="height"
              placeholder="请输入"
              :min="0"
              :max="1334"
              @change="inputChangeHeight"
            />
          </div> -->
          <div class="flex flex-a-c mt-m">
            <label class="nowrap text666 w-26n text-align-left">距左边距：</label>
            <a-input-number
              class="flex-1"
              :model-value="left"
              placeholder="请输入"
              :min="0"
              @change="inputChangeLeft"
            />
          </div>
          <div class="flex flex-a-c mt-m text-align-left">
            <label class="nowrap text666 w-26n">距上边距：</label>
            <a-input-number class="flex-1" :model-value="top" placeholder="请输入" :min="0" @change="inputChangeTop" />
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { uploadImage } from '@/apis'
import { getToken } from '@/utils/auth'
import { Message } from '@arco-design/web-vue'
defineOptions({ name: 'MsPoster' })
// 上传组件需要增加token
const tokenSource = getToken()
const token = tokenSource ? `Bearer ${tokenSource}` : ''
const emit = defineEmits(['update:poster', 'update:width', 'update:height', 'update:top', 'update:left', 'resetPoster'])
const loading = ref(false)
const fileList = ref([])
const realFileList = ref([]) //真实的上传列表
const props = defineProps({
  poster: {
    default: [],
    type: Array
  },
  width: {
    default: undefined,
    type: Number
  },
  // height: {
  //   default: undefined,
  //   type: Number
  // },
  top: {
    default: undefined,
    type: Number
  },
  left: {
    default: undefined,
    type: Number
  },
  showReset: {
    default: false,
    type: Boolean
  }
})
let picWO = null
// let picHO = null
let picTO = null
let picLO = null
const picW = computed(() => {
  return props.width / 4 || props.height / 4
})
// const picH = computed(() => {
//   return props.height / 4 || props.width / 4
// })
const picT = computed(() => {
  return props.top / 4
})
const picL = computed(() => {
  return props.left / 4
})
const deletePoster = (index) => {
  const posterA = props.poster
  posterA.splice(index, 1)
  emit('update:poster', posterA)
  if (posterA.length === 0) {
    emit('update:width', undefined)
    emit('update:top', undefined)
    emit('update:left', undefined)
  }
}
const resetPoster = () => {
  emit('update:width', picWO)
  emit('update:top', picTO)
  emit('update:left', picLO)
}
const centerPoster = () => {
  const widthO = props.width || 200
  emit('update:left', (750 - widthO) / 2)
}
// 上传图片成功改变
const handleUploadSuccess = (fileItem) => {
  realFileList.value = [
    {
      uid: fileItem.uid,
      name: fileItem.name,
      url: fileItem.response.data.url
    }
  ]
  loading.value = false
  const posterA = props.poster
  posterA.push(fileItem.response.data.url)
  emit('update:poster', posterA)
}
// 上传失败
const handleUploadError = (e) => {
  loading.value = false
  Message.error(e.response.message)
}
watch(
  () => props.poster,
  (str) => {
    if (str) {
      fileList.value = [
        {
          uid: 1,
          name: '1.png',
          url: str
        }
      ]
    } else {
      fileList.value = []
    }
    realFileList.value = JSON.parse(JSON.stringify(fileList.value))
  },
  { deep: true, immediate: true }
)
const inputChangeWidth = (e) => {
  emit('update:width', e)
}
const inputChangeHeight = (e) => {
  emit('update:height', e)
}
const inputChangeTop = (e) => {
  emit('update:top', e)
}

// 开始拖拽
const dragstart = (e) => {
  e.dataTransfer.setData('text', e.target.id)
}

// 鼠标松开事件
const drop = (e) => {
  e.preventDefault()
  const data = e.dataTransfer.getData('text')
  const draggedElement = document.getElementById(data)
  if (draggedElement) {
    e.target.appendChild(draggedElement)
  }
}
const inputChangeLeft = (e) => {
  emit('update:left', e)
}
</script>
<style lang="scss" scoped>
.poster_wrap {
  width: 187.5px;
  height: 333.5px;
  position: relative;
  .qr_wrap {
    position: absolute;
    cursor: move;
  }
}
.bg64f0f6fd {
  background: rgb(var(--primary-1));
}
</style>
